package com.tianheng.wanzhou.datacollecting.netty.autoPackage2.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.db.entity.AutoPackage2;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IAutoPackage2Service;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.Data;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import com.tianheng.wanzhou.datacollecting.util.TqlHexchange;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: yujw
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "autoPackage2Handler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IAutoPackage2Service autoPackageService;
    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        autoPackageService = this.autoPackageService;
//        jedis = this.jedis;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 10).eq("status", 1).eq("son_type", "04");
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inSocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();

//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));

        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            String data = str.substring(22);
            AutoPackage2 autoPackage = new AutoPackage2();
            autoPackage.setMachineIp(machine.getMacIp());
            autoPackage.setMacId(machine.getMacId());
            autoPackage.setCompany(machine.getCompany());
            autoPackage.setWorkshop(machine.getWorkshop());
            autoPackage.setTypeOfStackerBeltLine(TqlHexchange.fz4String(data.substring(0,4)));
            autoPackage.setStacker1Type(TqlHexchange.fz4String(data.substring(4,8)));
            autoPackage.setStacker2Type(TqlHexchange.fz4String(data.substring(8,12)));
            autoPackage.setCurrentPackageWeight(TqlHexchange.fz4String(data.substring(160,164)));
            autoPackage.setCurrentClassPackageNum(TqlHexchange.fz4String(data.substring(200,204)));
            autoPackage.setCumulativeNumberOfPackages(TqlHexchange.fz4String(data.substring(204,208)));
            autoPackageService.saveOrUpdate(autoPackage);

        }finally {
            ReferenceCountUtil.release(msg);
        }
        ctx.channel().close();
        ctx.close();
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
